package com.ali.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

/**
 * AIO
 */
public class AIOMain {
    public static void main(String[] args) {
        try {
            //构建监听服务
            AsynchronousServerSocketChannel asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            //绑定监听端口
            asynchronousServerSocketChannel.bind(new InetSocketAddress(8080));
            //监听客户端连接
            asynchronousServerSocketChannel.accept(null, new CompletionHandler<>() {
                @Override
                public void completed(AsynchronousSocketChannel result, Object attachment) {
                    System.out.println("接收客户端连接");
                    System.out.println("线程名：" + Thread.currentThread().getName());

                    try {
                        //构建缓冲区
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1);
                        int length;
                        while (true) {
                            //阻塞，等待数据传输，数据传输后写入内容至缓冲区
                            length = result.read(byteBuffer).get();
                            if (length > 0) {
                                System.out.println("接收内容：" + new String(byteBuffer.array(), 0, length));
                                //清理缓冲区
                                byteBuffer.clear();
                            } else if (length == -1) {
                                System.out.println("客户端断开连接");
                                break;
                            }
                        }
                    } catch (InterruptedException | ExecutionException e) {
                        throw new RuntimeException(e);
                    }

                    //监听客户端连接
                    asynchronousServerSocketChannel.accept(null, this);
                }

                @Override
                public void failed(Throwable exc, Object attachment) {
                }
            });
            //无限期休眠，防止主进程结束
            Thread.sleep(Integer.MAX_VALUE);
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
